package com.Register.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.Register.constant.ClassificationConstant;
import com.Register.constant.MessageConstant;
import com.Register.constant.StatusConstant;
import com.Register.dto.AdminUpdateDTO;
import com.Register.dto.AdminUpdatePasswordDTO;
import com.Register.dto.UserWebLoginDTO;
import com.Register.dto.WxUserPageQueryDTO;
import com.Register.entity.Carousel;
import com.Register.entity.PageQuery;
import com.Register.entity.User;
import com.Register.entity.WxUser;
import com.Register.exception.AccountNotAdminException;
import com.Register.exception.AccountNotFoundException;
import com.Register.exception.PasswordErrorException;
import com.Register.mapper.UserMapper;
import com.Register.mapper.WxUserMapper;
import com.Register.result.PageResult;
import com.Register.result.Result;
import com.Register.service.AdminService;
import com.Register.service.WxUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<UserMapper, User> implements AdminService {

    @Resource
    private  UserMapper userMapper;

    @Autowired
    private final PasswordEncoder passwordEncoder;

    @Resource
    private WxUserMapper wxUserMapper;

    /**
     * 网页端管理员登录
     * @param userWebLoginDTO
     * @return
     */
    @Override
    public User webAdminLogin(UserWebLoginDTO userWebLoginDTO) {
        String username = userWebLoginDTO.getUsername();
        String password = userWebLoginDTO.getPassword();

        //通过web端账号密码查询用户信息
        //1、判断用户是否存在
        User user = checkUserExist(username);

        //2.判断此账号是否为管理员
        if(!user.getClassification().equals(ClassificationConstant.ADMIN_USER)){
            //登录的不是管理员账号
            throw new AccountNotAdminException(MessageConstant.NOT_ADMIN);
        }

        //3、判断密码是否正确
        if(!passwordEncoder.matches(password,user.getPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //4、判断status，看账号是否被锁定
        if (user.getStatus().equals(StatusConstant.DISABLE)){
            //账号被锁定
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_LOCKED);
        }


        return user;
    }

    /**
     * 管理员修改密码
     * @param adminUpdatePasswordDTO
     * @return
     */
    @Override
    public boolean changePasswordByPhone(AdminUpdatePasswordDTO adminUpdatePasswordDTO) {
        //获取用户对象
        User user=checkUserExist(adminUpdatePasswordDTO.getUsername());
        if(user==null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        else if(Objects.equals(adminUpdatePasswordDTO.getPhone(), user.getPhone())) {
                user.setPassword(passwordEncoder.encode(adminUpdatePasswordDTO.getNewPassword())); // 对密码进行加密
                System.out.println(user.getPassword());
                userMapper.updateById(user);
                return true;
        }
        return false;
    }

    /*
    管理员禁用用户账号
     */
    @Override
    public void setUserBan(Long userId) {
        wxUserMapper.deleteById(userId);
    }

    @Override
    public void setUserActive(Long userId) {
        wxUserMapper.setUserActive(userId);
    }

    @Override
    public PageResult getAllWxUser(WxUserPageQueryDTO wxUserPageQueryDTO) {
        //构建分页条件
        Page<WxUser> page=wxUserPageQueryDTO.toMpPageDefaultSortByCreateTimeDesc();

        //构建查询条件
        LambdaQueryWrapper<WxUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();

        lambdaQueryWrapper
                .like(wxUserPageQueryDTO.getUsername()!=null,WxUser::getUsername,
                        wxUserPageQueryDTO.getUsername())
                .eq(wxUserPageQueryDTO.getCareer()!=null,WxUser::getCareer,
                        wxUserPageQueryDTO.getCareer())
                .like(wxUserPageQueryDTO.getOrganization()!=null,WxUser::getOrganization,
                        wxUserPageQueryDTO.getOrganization())
                .like(wxUserPageQueryDTO.getName()!=null,WxUser::getName,
                        wxUserPageQueryDTO.getName());
        Page<WxUser> wxUserPage=wxUserMapper.selectPage(page,lambdaQueryWrapper);
        //总页数
        long pages = wxUserPage.getPages();
        //总记录数
        long total = wxUserPage.getTotal();
        //当前页数据
        List<WxUser> records = wxUserPage.getRecords();

        return new PageResult(pages,total,records);
    }

    @Override
    public PageResult selectWxUserIsDeleted(PageQuery wxUserPageQueryDTO) {

        //总页数
        long pages = wxUserPageQueryDTO.getPageNo();
        //总记录数
        long total = wxUserPageQueryDTO.getPageSize();
        //当前页数据
        List<WxUser> records = wxUserMapper.selectUserIsDeleted();

        return new PageResult(pages,total,records);
    }

    @Override
    public Result<String> AdminUpdate(AdminUpdateDTO adminUpdateDTO) {
        User user=userMapper.selectById(adminUpdateDTO.getId());
        user.setUpdateTime(LocalDateTime.now());
        BeanUtil.copyProperties(adminUpdateDTO,user);
        userMapper.updateById(user);
        return Result.success("更新成功");
    }

    /**
     * 通过用户名检查用户是否存在
     * @param username
     * @return
     */
    public User checkUserExist(String username)  {
        //通过web端账号密码查询用户信息
        //1、判断用户是否存在
        User user = userMapper.selectByUsername(username);
        if (user==null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        return user;
    }
}
